package com.edu.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @作者 five-five
 * @创建时间 2021/1/20
 */
//@Configuration
//@EnableWebSecurity
public class TestWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    /**
     * 授权
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭csrf
        http.csrf().disable();
        //支持httpbasic
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();

        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1").hasRole("role1")
                .antMatchers("/level2").hasRole("role2")
                .antMatchers("/level3").hasRole("role3");
        //没有权限默认跳转到登录页面，需要开启登录的页面
        http.formLogin();
        //开启了注销功能
        http.logout()
                .deleteCookies("remove")
                .invalidateHttpSession(true)
                .logoutUrl("/index")
                .logoutSuccessUrl("/index");

    }

    /**
     * 认证，springboot2.1.x可以直接使用
     * 密码：必须使用密码编码器
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("root1").password(new BCryptPasswordEncoder().encode("admin123")).roles("superAdmin")
                .and().withUser("root2").password(new BCryptPasswordEncoder().encode("admin123")).roles("superAdmin")
                .and().withUser("root3").password(new BCryptPasswordEncoder().encode("admin123")).roles("superAdmin");

    }
}
